package com.syni.mdd.sjb.common.gateway.filter;

import com.syni.mdd.sjb.common.gateway.utils.CDPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 请求Filter
 * 判断是否CDP请求
 *
 * @author Mr.Bean
 * @date 2021/3/1 10:21
 */
@Component
public class RequestFilter implements GlobalFilter, Ordered {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 获取url路径并解析
		ServerHttpRequest request = exchange.getRequest();
		URI uri = request.getURI();
		String path = uri.getPath();
		if (path.contains("/cdp")) {
			log.info("###cdp url###：" + uri);
			// 获取请求体
			Flux<DataBuffer> body = request.getBody();
			AtomicReference<String> bodyRef = new AtomicReference<>();
			body.subscribe(buffer -> {
				CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
				DataBufferUtils.release(buffer);
				bodyRef.set(charBuffer.toString());
			});
			String bodyStr = bodyRef.get();
			// 调用cdp接口
			String result = CDPUtil.post(path, bodyStr);
			byte[] bytes = result.getBytes(StandardCharsets.UTF_8);
			DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
			// 直接返回接口数据
			return exchange.getResponse().writeWith(Flux.just(buffer));
		}
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 99;
	}
}
